<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!--搜索与添加区-->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="addDialogShow()">添加分类</el-button>
        </el-col>
      </el-row>
    </el-card>
    <tree-table :data="categoriesList" :columns="columns" :selection-type="false" :expand-type="false" show-index index-text="#" border :show-row-hover="false">
      <!-- 自定义列 是否有效 -->
      <template slot="isOk" slot-scope="scope">
        <i class="el-icon-success" style="color:lightgreen" v-if="scope.row.cat_deleted === false"></i>
        <i class="el-icon-error" style="color:lightgreen" v-else></i>
      </template>
      <!-- 排序 -->
      <template slot="order" slot-scope="scope">
        <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
        <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
        <el-tag v-else type="danger">三级</el-tag>
      </template>
      <!-- 操作 -->
      <template slot="opt" slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit" size="mini" @click="getCateById(scope.row.cat_id)">编辑</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCateById(scope.row.cat_id)">删除</el-button>
      </template>
    </tree-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" @close="addDilogClose()">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader v-model="selectedKeys" :options="parentCateList" :props="cascaderProps" @change="handleChange">
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDilogClose()">取 消</el-button>
        <el-button type="primary" @click="addCat()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类 -->
    <el-dialog title="编辑分类" :visible.sync="eidtDialogVisible" width="50%" @close="editDilogClose()">
      <el-form :model="editForm" ref="editFormRef" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDilogClose()">取 消</el-button>
        <el-button type="primary" @click="editCat()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  categoryList,
  categoryAdd,
  categoryLoad,
  categoryEdit,
  categoryDel,
} from "@/request/api";
import Vue from "vue";
import TreeTable from "vue-table-with-tree-grid";
import { Component, Ref } from "vue-property-decorator";
import { ElForm } from "element-ui/types/form";
@Component({
  components: {
    TreeTable,
  },
})
export default class Category extends Vue {
  // 商品分类列表
  categoriesList: [] = [];
  queryInfo: {
    type: number;
    pagenum: number;
    pagesize: number;
  } = {
    type: 3,
    pagenum: 1,
    pagesize: 5,
  };
  total: number = 0;
  columns: Array<{
    label: string;
    // 自定义列
    type?: string;
    template?: string;
    prop?: string;
  }> = [
    {
      label: "分类名称",
      prop: "cat_name",
    },
    {
      label: "是否有效",
      // 自定义列
      type: "template",
      template: "isOk",
    },
    {
      label: "排序",
      // 自定义列
      type: "template",
      template: "order",
    },
    {
      label: "操作",
      // 自定义列
      type: "template",
      template: "opt",
    },
  ];
  addDialogVisible: boolean = false;
  addForm: {
    cat_name: string;
    cat_level: number;
    cat_pid: number;
  } = {
    cat_name: "",
    cat_level: 0,
    cat_pid: 0,
  };
  addFormRules: {} = {};
  // 保存父级分类数据
  parentCateList: [] = [];
  cascaderProps: {
    value: string;
    label: string;
    children: string;
    // 选择任意一项
    checkStrictly: boolean;
  } = {
    value: "cat_id",
    label: "cat_name",
    children: "children",
    // 选择任意一项
    checkStrictly: true,
  };
  // 选中的级联的数据
  selectedKeys: Array<number> = [];
  // 编辑分类相关操作
  eidtDialogVisible: boolean = false;
  editForm: {
    cat_deleted: boolean;
    cat_id: number;
    cat_level: number;
    cat_name: string;
    cat_pid: number;
  } = {
    cat_deleted: false,
    cat_id: 0,
    cat_level: 0,
    cat_name: "",
    cat_pid: 0,
  };
  created() {
    this.getCategoriesList();
  }
  // 获取商品分类列表
  async getCategoriesList() {
    const { data, meta } = await categoryList(this.queryInfo);
    if (meta.status !== 200) return this.$message.error("获取列表数据据失败");
    this.categoriesList = data.result;
    this.total = data.total;
  }
  // 每页显示数据改变触发的事件
  handleSizeChange(newPageSize: number) {
    this.queryInfo.pagesize = newPageSize;
    this.getCategoriesList();
  }
  // 页数切换触发的事件
  handleCurrentChange(newCurrent: number) {
    this.queryInfo.pagenum = newCurrent;
    this.getCategoriesList();
  }
  // 添加商品分类
  async addCat() {
    console.log(this.addForm);
    const { data, meta } = await categoryAdd(this.addForm);
    if (meta.status !== 201) return this.$message.error("创建商品分类失败");
    this.$message.success(meta.msg);
    this.getCategoriesList();
    this.addDialogVisible = false;
  }
  addDialogShow() {
    // 获取级联数据
    this.getParentCateList();
    this.addDialogVisible = true;
  }
  // 获取父级的分类列表
  async getParentCateList() {
    const { data, meta } = await categoryList({ type: 3 });
    if (meta.status !== 200) return this.$message.error("获取父级分类失败");
    this.parentCateList = data;
  }
  handleChange() {
    // 商品父级分类cat_pid为选中项的最后一项
    if (this.selectedKeys.length > 0) {
      this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
      this.addForm.cat_level = this.selectedKeys.length;
      console.log(this.selectedKeys);
    } else {
      this.addForm.cat_pid = 0;
      this.addForm.cat_level = 0;
    }
  }
  @Ref("addFormRef") addFormRef!: ElForm;
  // 添加分类框关闭事件
  addDilogClose() {
    this.addFormRef.resetFields();
    this.selectedKeys = [];
    this.addForm.cat_pid = 0;
    this.addForm.cat_level = 0;
  }
  // 根据id获取对应的分类数据
  async getCateById(id: number) {
    const { data, meta } = await categoryLoad(id);
    if (meta.status !== 200) return this.$message.error("获取分类失败");
    this.eidtDialogVisible = true;
    this.editForm = data;
  }
  // 编辑分类数据并保存
  async editCat() {
    const { data, meta } = await categoryEdit(this.editForm.cat_id, {
      cat_name: this.editForm.cat_name,
    });
    if (meta.status !== 200) return this.$message.error("更新数据失败");
    this.getCategoriesList();
    this.$message.success(meta.msg);
    this.eidtDialogVisible = false;
  }
  // 根据id删除单个分类
  async deleteCateById(id: number) {
    const confirmRes = await this.$confirm(
      "此操作将永久删除该分类, 是否继续?",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    ).catch((err) => {
      return err;
    });
    if (confirmRes !== "confirm") return this.$message.error("取消了删除操作");
    const { data, meta } = await categoryDel(id);
    if (meta.status !== 200) return this.$message.error("删除分类失败");
    this.getCategoriesList();
    this.$message.success("删除分类成功");
  }
  @Ref("editFormRef") editFormRef!: ElForm;
  // 编辑分类窗口关闭事件
  editDilogClose() {
    this.editFormRef.resetFields();
    this.eidtDialogVisible = false;
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 5px;
}
.tbtop {
  border-top: 1px solid #eee;
}
.tbbottom {
  border-bottom: 1px solid #eee;
}
.tagmiddle {
  display: flex;
  align-items: center;
}
.el-cascader {
  width: 100%;
}
</style>